/**
 * Created by huotaol on 2017/6/7.
 */
import React, {Component} from "react";
import PropTypes from "prop-types";
import {Image, InteractionManager, ListView, ScrollView, StyleSheet, Text, TouchableOpacity, View} from "react-native";
import CustomStyle from "../../../common/style/CustomStyle";
import ModuleCommonHeader from "../../main/module/ModuleCommonHeader";
import {Actions} from "react-native-router-flux";
import Util from "../../main/Util";
import SectionTitle from "../../main/mainUI/components/SectionTitle";
import CheckDescriptionItem from "../cardetail/component/CheckDescriptionItem";
import LoadingView from "../../../common/component/LoadingView";

const LIST_DATA_SOURCE = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

export default class HelpLookDetail extends Component {

    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            loading: true,
            carInfo: {},
        };
        this._fetchCarInfo = this._fetchCarInfo.bind(this);
    }

    componentDidMount() {
        InteractionManager.runAfterInteractions(() => {
            this._fetchCarInfo(this.props.carNum);
        });
    }

    render() {
        if (this.state.loading) {
            return <LoadingView/>
        }
        const carBasicInfo = this.state.carInfo.carsinfo;
        console.log('HelpLookDetail render ' + JSON.stringify(this.state.carInfo));
        const handelLine = [];
        handelLine.push({title: `${carBasicInfo.travelkilometer}万公里`, content: '里程数'});
        handelLine.push({title: carBasicInfo.firstrecorddate, content: '上牌时间'});
        handelLine.push({title: carBasicInfo.carterritorial, content: '车牌所在地'});
        handelLine.push({title: carBasicInfo.emissionstandard, content: '排放标准'});
        handelLine.push({title: carBasicInfo.transmissiontype, content: '变速箱'});
        handelLine.push({title: carBasicInfo.displacement, content: '排放量'});
        return (
            <View style={{flex: 1}}>
                <ModuleCommonHeader title={`车辆编号：${this.props.carNum}`}/>
                <ScrollView style={{flex: 1, backgroundColor: '#FFfcee',}}>
                    <View style={{
                        backgroundColor: '#ffc000',
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        width: CustomStyle.screenWidth,
                        height: CustomStyle.getActualSizeInVertical(80),
                    }}/>
                    <View style={[styles.basicInfoContainer]}>
                        <Text style={[CustomStyle.baseText, {
                            fontSize: CustomStyle.getActualFontSize(30),
                            color: '#4a3d18',
                            alignSelf: 'center',
                            marginTop: CustomStyle.getActualSizeInVertical(70),
                        }]}>{carBasicInfo.carbrand + ' ' + carBasicInfo.carseries + ' ' + carBasicInfo.carmodel}</Text>
                        {this._renderScore(carBasicInfo)}
                        <View
                            style={{
                                paddingLeft: CustomStyle.getActualSizeInHorizontal(38),
                                flexDirection: 'row',
                                alignItems: 'flex-end',
                            }}
                        >
                            <Text style={[CustomStyle.baseText, {
                                fontSize: CustomStyle.getActualFontSize(60),
                                color: '#ff2d22',
                                textAlignVertical: 'bottom',
                                fontWeight: 'bold',
                            }]}>{carBasicInfo.presaleprice}<Text
                                style={{fontSize: CustomStyle.getActualFontSize(26)}}>万</Text></Text>
                            {carBasicInfo.reducePriceText ? <View style={{
                                backgroundColor: 'white', borderWidth: CustomStyle.getActualSizeInHorizontal(2),
                                borderRadius: CustomStyle.getActualSizeInHorizontal(4), borderColor: "#ff7200",
                                height: CustomStyle.getActualSizeInVertical(38),
                                marginLeft: CustomStyle.getActualSizeInHorizontal(20),
                            }}>
                                <Text style={[CustomStyle.baseText, {
                                    fontSize: CustomStyle.getActualFontSize(),
                                    color: '#ff7200',
                                }]}>{carBasicInfo.reducePriceText}</Text>
                            </View> : null}
                        </View>

                        <View
                            style={[styles.basicInfoHandleContainer, {marginTop: CustomStyle.getActualSizeInVertical(58),}]}>
                            {handelLine.slice(0, 3).map(item => <BasicHandleCard style={[styles.basicInfoHandleItem]}
                                                                                 title={item.title}
                                                                                 subContent={item.content}/>)}
                        </View>
                        <View
                            style={[styles.basicInfoHandleContainer, {marginTop: CustomStyle.getActualSizeInVertical(58),}]}>
                            {handelLine.slice(3).map(item => <BasicHandleCard style={[styles.basicInfoHandleItem]}
                                                                              title={item.title}
                                                                              subContent={item.content}/>)}
                        </View>
                        <TouchableOpacity style={{
                            alignItems: 'center',
                            flexDirection: 'row',
                            height: CustomStyle.getActualSizeInVertical(88),
                            borderTopWidth: CustomStyle.getActualSizeInVertical(1),
                            borderTopColor: 'rgba(0,0,0,0.4)',
                            marginTop: CustomStyle.getActualSizeInVertical(40),
                            justifyContent: 'center',
                        }}
                                          onPress={() => {
                                              Actions.HelpAllParam({carInfo: carBasicInfo});
                                          }}
                        >
                            <Image source={require('../../../img/cardetail/all.png')} style={{
                                width: CustomStyle.getActualSizeInHorizontal(30),
                                height: CustomStyle.getActualSizeInVertical(20),
                                resizeMode: 'center',
                            }}/>
                            <Text style={[CustomStyle.baseText, {
                                fontSize: CustomStyle.getActualFontSize(28),
                                color: '#857e6e',
                                marginLeft: CustomStyle.getActualSizeInHorizontal(20),
                            }]}>全部参数</Text>
                        </TouchableOpacity>
                    </View>

                    <View style={[styles.guaranteeContainer, {}]}>
                        <SectionTitle title={'检测报告'}/>
                        <ListView
                            renderSeparator={this._renderSeparator}
                            dataSource={LIST_DATA_SOURCE.cloneWithRows(this._processCheckList(this.state.carInfo))}
                            renderRow={item => {
                                console.log('HelpLookDetail item  ' + JSON.stringify(item));
                                return <CheckDescriptionItem image={item.image} title={item.title}
                                                             normalNum={item.normalNum}
                                                             exceptionNum={item.exceptionNum}
                                                             click={() => {
                                                                 Actions.HelpCheckParamDetail({
                                                                     title: item.title,
                                                                     sign: item.sign,
                                                                     carData: this.state.carInfo,
                                                                 });
                                                             }}/>
                            }}/>
                    </View>
                </ScrollView>
            </View>
        );
    }

    _renderScore(carData) {
        let accredit = parseInt(carData.isaccred);
        if (1 || accredit > 0) {
            return <Image source={require('../../../img/cardetail/score.png')} style={{
                position: 'absolute',
                left: CustomStyle.getActualSizeInHorizontal(20),
                top: 0,
                height: CustomStyle.getActualSizeInVertical(80),
                width: CustomStyle.getActualSizeInHorizontal(72),
                alignItems: 'center',
                paddingTop: CustomStyle.getActualSizeInVertical(8),
            }}><Text style={[CustomStyle.baseText, {
                fontSize: CustomStyle.getActualFontSize(30),
                color: 'white',
            }]}>{Math.floor(carData.totalscore)}</Text></Image>
        }
    }

    _fetchCarInfo(carNum) {
        const api = 'user/querybkcarsdetail';
        const param = {
            carid: carNum,
        };
        Util.postServer(api, param, result => {
            console.log('HelpLookDetail  success ' + JSON.stringify(result));
            this.setState({carInfo: result.data, loading: false});
        }, msg => {
            console.log('HelpLookDetail failed ' + msg);
            Util.showToast(msg);
            Actions.pop();
        });
    }


    _renderSeparator() {
        return <View style={[CustomStyle.separator]}>
        </View>;
    }

    _processCheckList(data) {
        const checkList = [];
        checkList.push({
            image: require('../../../img/cardetail/skeleton_small.png'),
            title: '车辆骨架',
            exceptionNum: data.framecount.frame_error,
            normalNum: data.framecount.frame_total - data.framecount.frame_error,
            sign: 'carframe',
        });
        checkList.push({
            image: require('../../../img/cardetail/engin_small.png'), title: '发动机舱',
            exceptionNum: data.enginecount.engine_error,
            normalNum: data.enginecount.engine_total - data.enginecount.engine_error,
            sign: 'carengine',
        });
        checkList.push({
            image: require('../../../img/cardetail/start_small.png'), title: '启动检查',
            exceptionNum: data.startcount.start_error,
            normalNum: data.startcount.start_total - data.startcount.start_error,
            sign: 'carstart',
        });
        checkList.push({
            image: require('../../../img/cardetail/driving_small.png'),
            title: '驾驶舱',
            exceptionNum: data.cockpitcount.cockpit_error,
            normalNum: data.cockpitcount.cockpit_total - data.cockpitcount.cockpit_error,
            sign: 'carcockpit',
        });
        checkList.push({
            image: require('../../../img/cardetail/outlook_small.png'),
            title: '车身外观',
            exceptionNum: data.facecount.face_error,
            normalNum: data.facecount.face_total - data.facecount.face_error,
            sign: 'carface',
        });
        checkList.push({
            image: require('../../../img/cardetail/unit_small.png'),
            title: '功能性零部件',
            exceptionNum: data.partscount.parts_error,
            normalNum: data.partscount.parts_total - data.partscount.parts_error,
            sign: 'carfunparts',
        });
        return checkList;
    }

}

class BasicHandleCard extends Component {
    static propTypes = {
        title: PropTypes.string,
        subContent: PropTypes.string,
        click: PropTypes.func,
    };
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {};
    }

    render() {
        return (
            <TouchableOpacity
                style={this.props.style}
                onPress={this.props.click}>
                <Text
                    numberOfLines={1}
                    style={[CustomStyle.baseText, {
                        fontSize: CustomStyle.getActualFontSize(30),
                        color: '#4a3d18',
                    }]}>{this.props.title}</Text>
                <Text
                    style={[CustomStyle.baseText, {
                        fontSize: CustomStyle.getActualFontSize(24),
                        color: '#857e6e',
                        marginTop: CustomStyle.getActualSizeInVertical(20),
                    }]}>{this.props.subContent}</Text>
            </TouchableOpacity>
        );
    }
}


const styles = StyleSheet.create({
    basicInfoContainer: {
        backgroundColor: 'white',
        borderTopLeftRadius: CustomStyle.getActualSizeInHorizontal(20),
        borderTopRightRadius: CustomStyle.getActualSizeInHorizontal(20),
        marginLeft: CustomStyle.getActualSizeInHorizontal(20),
        marginRight: CustomStyle.getActualSizeInHorizontal(20),
    },
    basicInfoHandleContainer: {
        flexDirection: 'row',
    },
    guaranteeContainer: {
        backgroundColor: 'white',
        paddingTop: CustomStyle.getActualSizeInVertical(40),
        paddingLeft: CustomStyle.getActualSizeInHorizontal(20),
        paddingRight: CustomStyle.getActualSizeInHorizontal(20),
        paddingBottom: CustomStyle.getActualSizeInVertical(40),
        marginTop: CustomStyle.getActualSizeInVertical(20),
    },
    basicInfoHandleItem: {
        flex: 1,
        alignItems: 'center',
    },

});